package com.gitee.lougnib.simple.lang.util;

import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.Objects;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class LPropertiesUtils {

	private static final Logger LOGGER = LoggerFactory.getLogger(LPropertiesUtils.class);

	/**
	 * 缓存属性文件
	 */
	private static Map<String, Properties> propertiesCache = new ConcurrentHashMap<>();

	private static final String DEFAULT_SUFFIX = "-default";

	public static <T> T getProperty(String propertiesName, String key, Class<T> clazz) {
		Properties properties = getProperties(propertiesName);
		if (!Objects.isNull(properties)) {
			String value = properties.getProperty(key);
			if (StringUtils.isEmpty(value)) {
				return null;
			}

			if (clazz == Boolean.class) {
				return clazz.cast(Boolean.parseBoolean(value));
			} else if (clazz == Integer.class) {
				return clazz.cast(Integer.parseInt(value));
			} else if (clazz == Long.class) {
				return clazz.cast(Long.parseLong(value));
			} else if (clazz == Double.class) {
				return clazz.cast(Double.parseDouble(value));
			} else {
				return clazz.cast(value);
			}

		}

		return null;
	}

	public static Properties getProperties(String propertiesName) {
		return getProperties(propertiesName, true);
	}

	public static Properties getProperties(String propertiesName, boolean toCache) {
		Properties properties = propertiesCache.get(propertiesName);

		if (properties == null) {
			Properties defaultProperties = loadProperties(propertiesName + DEFAULT_SUFFIX);
			properties = loadProperties(propertiesName);

			if (defaultProperties != null && properties != null) {
				defaultProperties.putAll(properties);
				properties = defaultProperties;
			} else if (defaultProperties != null) {
				properties = defaultProperties;
			}

			if (toCache && properties != null) {
				propertiesCache.put(propertiesName, properties);
			}
		}

		return properties;
	}

	private static Properties loadProperties(String propertiesName) {
		Properties properties = null;
		StringBuilder propertiesPath = new StringBuilder(propertiesName);
		if (!StringUtils.startsWith(propertiesPath, "/")) {
			propertiesPath.insert(0, "/");
		}
		if (!StringUtils.endsWith(propertiesPath, ".properties")) {
			propertiesPath.append(".properties");
		}
		try (InputStream in = LPropertiesUtils.class.getResourceAsStream(propertiesPath.toString())) {
			properties = new Properties();
			properties.load(in);
		} catch (IOException e) {
			LOGGER.error(e.getMessage(), e);
		}
		return properties;
	}
}
